Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

325
Visualizações
How to define a class method :[] when using class_eval

I am using the quaternion gem and want to define a class method for the :[] operator that creates a new Quaternion from an array. I have tried

Quaternion.class_eval do
  def self.[ary]
    Quaternion.new(*ary)
  end
end

but this gives a syntax error. How do I do this?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The method's name is [], but it still takes its argument list in the usual way

def self.[](ary)
  ...
end

Then you call it as Quaternion[ary]

over 4 years ago · Santiago Trujillo Relatório

0

So long story short to be able to make use of Quaternion[arg] you want to define it like below

  def self.[](arg)
    Quaternion.new(*ary)
  end

interesting is, why does it work? Well it's syntactic sugar that ruby has

doing foo[bar] is the same as foo.[](bar)

foo[bar]=baz is the same as foo.[]=(bar, baz)

and a + b is actually a.+(b)

If you want to define it, it will look like this:

def [](key)
  ...
end

def []=(key, value)
  ...
end

def +(arg)
  ...
end

It's because method names in ruby can have special characters.

If you are interested in how internally it gets tokenized and parsed you can read Ruby Under Microscope which is a great introduction to the subject. There is also this free book I've found which also touches on the topic -> https://ruby-hacking-guide.github.io/ (check chapter 8 section Method Calls)

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda